package com.blank.shop.ssr.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 天猫亿级UV的Redis统计方案
 *
 * @author _blank
 */
@Slf4j
@RestController
public class HyperLogLogController implements InitializingBean {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private ThreadPoolTaskExecutor applicationTaskExecutor;

    /**
     * 无效    @Async(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("------模拟后台有用户点击首页，每个用户来自不同ip地址");

        Runnable runnable = () -> {
            for (int i = 1; i <= 20; i++) {
                final String ip = StringUtils.joinWith("."
                        , RandomUtils.nextInt(0, 256)
                        , RandomUtils.nextInt(0, 256)
                        , RandomUtils.nextInt(0, 256)
                        , RandomUtils.nextInt(0, 256));

                final Long hll = this.redisTemplate.opsForHyperLogLog().add("hll", ip);
                log.info("ip={},该ip地址访问首页的次数={}", ip, hll);

                try {
                    // 暂停几秒钟线程
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    log.error(e.getMessage(), e);
                    Thread.currentThread().interrupt();
                }
            }
        };
        this.applicationTaskExecutor.submit(runnable);
    }

    /**
     * 获得IP去重后的首页访问量
     *
     * @return org.springframework.http.ResponseEntity
     */
    @GetMapping(path = {"/uv"})
    public ResponseEntity<Long> uv() {
        //pfcount
        final Long size = redisTemplate.opsForHyperLogLog().size("hll");
        return ResponseEntity.ok(size);
    }

}
